const db = require("../db")
const bcrypt = require('bcryptjs')
// 用这个包来生成 Token 字符串
const jwt = require('jsonwebtoken')
const date = require("silly-datetime");
const config = require('../config/config.js')
const today = date.format(new Date(),'YYYY-MM-DD HH:mm:ss'); 
/**
 * 随机生成字符串
 * @param len 指定生成字符串长度
 */
 function getRandomString(len){
    let _charStr = 'abacdefghjklmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789',
        min = 0, 
        max = _charStr.length-1, 
        _str = '';                    //定义随机字符串 变量
    //判断是否指定长度，否则默认长度为15
    len = len || 15;
    //循环生成字符串
    for(var i = 0, index; i < len; i++){
        index = (function(randomIndexFunc, i){         
                    return randomIndexFunc(min, max, i, randomIndexFunc);
                })(function(min, max, i, _self){
                    let indexTemp = Math.floor(Math.random()*(max-min+1)+min),
                        numStart = _charStr.length - 10;
                    if(i==0&&indexTemp >=numStart){
                        indexTemp = _self(min, max, i, _self);
                    }
                    return indexTemp ;
                }, i);
        _str += _charStr[index];
    }
    return _str;
}
exports.register = (req, res) => {
    // 接收表单数据
    const userinfo = req.body
    userinfo['username'] = getRandomString(10);
    userinfo['createTime'] = today
    userinfo['is_delete'] = 0
    userinfo['roleId'] = 4    // 注册用户默认为普通用户
    userinfo['userPic']='user.png' // 设置默认头像
    db.query('select * from user where username = ?',userinfo.username,function(err,result){
        if(err){
            return res.cc(err)
        }
        if(result.length > 0){
            return res.cc("用户名已被占用，请更换其他用户名！",-1)
        }
    })
    //对用户密码进行加密
    userinfo.password = bcrypt.hashSync(userinfo.password, 10)
    // 插入新用户
    db.query("insert into user set ?",userinfo,function(err,result){
        if(err){
            return res.cc(err)
        }
        if(result.affectedRows != 1){
            return res.cc("注册用户失败，请稍后重试！")
        }
        return res.cc("新增用户成功",200)
    })
}
// 后台登录页面
exports.login = (req, res) => {
    let userinfo = req.body
    // 用户名是否存在验证
    db.query("select * from user where username =? or phone = ? or email = ? and roleId <> 4 and roleId <> 5 and mg_state = 1",[userinfo.username,userinfo.username,userinfo.username],function(err,result){
        if(err){
            return res.cc(err)
        }
        if(result.length != 1) return res.cc('用户名不存在！','-1')
        if(!bcrypt.compareSync(userinfo.password,result[0].password)){
            return res.cc('密码错误，请重新输入','-1')
        }
        const tokenStr = jwt.sign({ username: result[0].nickName,id:result[0].id,avator:result[0].userPic }, config.jwtSecretKey, { expiresIn: '300h' })
        res.cookie("token",tokenStr).send({
            code: 200,
            msg: '登录成功！',
            // 为了方便客户端使用 Token，在服务器端直接拼接上 Bearer 的前缀
            token: 'Bearer ' + tokenStr,

          })
    })
}
// 前台登录页面
exports.shoplogin = (req,res)=>{
    let userinfo = req.body
    db.query('select * from user where (username = ? or phone = ? or email = ? ) and roleId in (4,5) ',[userinfo.username,userinfo.username,userinfo.username],function(err,result){
        if(err) return res.cc(err)
        if(result.length == 0 ) return res.cc("该用户不存在，请输入正确的账号名/邮箱/手机号")
        if(!bcrypt.compareSync(userinfo.password,result[0].password)){
            return res.cc("用户密码输入错误，请重新输入")
        } 
        const tokenStr = jwt.sign({ username: result[0].nickName,id:result[0].id,avator:result[0].userPic }, config.jwtSecretKey, { expiresIn: '30h' })
        return res.cookie("token",tokenStr).send({
            code:200,
            msg:"登录成功！",
            data:{
                id:result[0].id,
                nickName:result[0].nickName,
                token: 'Bearer ' + tokenStr,
            }
        })
    })
}

exports.shopUserDetail = (req,res)=>{
    let id = req.body.id
    db.query("select nickname,userPic from user where id = ?;select * from user_order where userId = ?",[id,id],function(err,result){
        if(err) return res.cc(err)
        return res.send({
            code:200,
            msg:"获取用户详细信息成功",
            data:result[0][0]
        })
    })
}

exports.getUserInfo = (req,res)=>{
    console.log(req.user);
    return res.send({
        code: 200,
        msg: '请求成功!',
        data: {
          username: req.user.username, //这里的username就来自于jwt字符串的解析,
          id:req.user.id,
          avator:req.user.avator
        }
      })
}